/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.project.carshop07.ctrl.jpa;

import edu.chl.project.carshop07.ctrl.jpa.exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author AMADIN
 */

public class JpaCtrl {

    
    private EntityManagerFactory emf;

    public JpaCtrl(EntityManagerFactory emf) {
        if(emf == null)
            throw new NullPointerException("EMF:null");
        this.emf = emf;
    }
    
    public JpaCtrl(String unitName) {
        this(Persistence.createEntityManagerFactory(unitName));
    }
    
    public EntityManager getEntityManager(){
        return emf.createEntityManager();
    }
    public  <T extends Serializable> void  create(T t){
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        em.persist(t);
        em.getTransaction().commit();
    }
    public  <T extends Serializable> void  destroy(long id, 
            Class<T> type) throws NonexistentEntityException {
         EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            T t;
            try {
                t = em.getReference(type, id);
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("Entity "+type.getSimpleName()
                        +" does not exist.", enfe);
            }        
            em.remove(t);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public <T extends Serializable> void edit(T t) 
            throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.merge(t);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                throw new NonexistentEntityException("Entity " + t.getClass().getSimpleName()
                        + " does not exist.");
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public <T extends Serializable> T findEntity(long id,  Class<T> type) {
        EntityManager em = getEntityManager();
       return em.find(type,id);
    }
    
    public <T extends Serializable> List<T> findEntities(Class<T> type) {
        return findEntities(true, -1, -1, type);
        
    }  
    public <T extends Serializable> List<T> findEntities(int maxResults, 
        int firstResult, Class<T> type) {
        return findEntities(false, maxResults, firstResult, type);
      
    }

    public <T extends Serializable> int getEntityCount(Class<T> type) {
        EntityManager em = getEntityManager();
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        Root<T> rt = cq.from(type);
        cq.select(em.getCriteriaBuilder().count(rt));
        Query q = em.createQuery(cq);
        return ((Long)q.getSingleResult()).intValue(); 
    }
    public <T extends Serializable> TypedQuery createQuery(String query, 
            Class<T> type){
        EntityManager em = getEntityManager();
        return em.createQuery(query, type);
    }
    
    public  Query createQuery(String query){
        EntityManager em = getEntityManager();
        return em.createQuery(query);
    }
    
    private <T extends Serializable> List<T> findEntities(boolean all, int maxResults, 
            int firstResult, Class<T> type) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(type));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }
    
}
